package day61_23;

import com.sun.org.apache.bcel.internal.generic.NEW;

/**
 * @ClassName Solution
 * @Description TODO
 * @Author clockTown
 * @Date 2021/7/10 21:36
 * @Version 1.0
 */
public class Solution {
    public ListNode mergeKLists(ListNode[] lists) {
        if (lists == null || lists.length == 0) {
            return null;
        }
        if (lists.length == 1) {
            return lists[0];
        }

        ListNode[] res = new ListNode[lists.length / 2];
        int i = 0, j = 1;

        while (j < lists.length) {
            ListNode listNode = mergeTwoListNode(lists[i], lists[j]);
            i += 2;
            j += 2;
        }
        return mergeKLists(res);
    }

    private ListNode mergeTwoListNode(ListNode l1, ListNode l2) {
        ListNode head = new ListNode(0);
        ListNode cur = head;
        while (l1 != null && l2 != null) {
            if (l1.val <= l2.val) {
                cur.next = l1;
                cur = cur.next;
                l1 = l1.next;
            } else {
                head.next = l2;
                cur = cur.next;
                l2 = l2.next;
            }
        }

        while (l1 != null) {
            cur.next = l1;
            cur = cur.next;
            l1 = l1.next;
        }
        while (l2 != null) {
            cur.next = l2;
            cur = cur.next;
            l2 = l2.next;
        }

        return head.next;

    }

    public static void main(String[] args) {
        ListNode l1 = new ListNode(new int[]{1, 4, 5});
        ListNode l2 = new ListNode(new int[]{1, 3, 4});
        ListNode l3 = new ListNode(new int[]{2, 6});
        ListNode[] lists = new ListNode[] {l1, l2, l3};
        System.out.println(new Solution().mergeKLists(lists));
    }
}
